package dao.impl;

import dao.BaseDao;
import dao.UserDao;
import pojo.Anime;
import pojo.Ratingrecord;
import pojo.User;

import java.util.*;

public class UserDaoImplement extends BaseDao implements UserDao {

    @Override
    public Object queryMaxID() {
        String sql="select max(cast(user_id as INTEGER)) from rat_user";
        return queryForMax(sql);

    }

    @Override
    public User queryUserbyId(String user_ID) {
        String sql="select * from rat_user where user_id=?";
        return queryForOne(User.class,sql,user_ID);
    }

    @Override
    public int saveUser(User user) {
        String sql="insert into rat_user values(?)";
        return update(sql,user.getUser_ID());
    }


    @Override
    public List<Anime> doRecommendation(String user_id) {
        String sql = "select * from filtrate_by_uid(?) limit 30";
        //找到用户评分较高的动漫
        List<Anime> AnimeList = queryForList(Anime.class, sql, user_id);
        if (AnimeList.size() < 5) {
            //评分获取数据过少，采用默认高分推荐
            String sql_recommendation = "select * from rat_anime where rating>?";
            List<Anime> recommendList = queryForList(Anime.class, sql, 8.0);
            return recommendList;
        } else {

            //统计不同的genre出现次数
            Map<String, Integer> keyCount = new HashMap<>();
            //遍历取出genre
            for (Anime anime : AnimeList) {
                String[] genreWrap = (anime.getGenre().toString().split("，"));
                for (int i = 0; i < genreWrap.length; i++) {
                    if (keyCount.get(genreWrap[i]) == null) {
                        keyCount.put(genreWrap[i], 1);
                    } else {
                        keyCount.put(genreWrap[i], keyCount.get(genreWrap[i]) + 1);
                    }
                }
            }
            //对keyCount中的genre进行排序
            List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(keyCount.entrySet());
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return (o2.getValue() - o1.getValue());
                }
            });

          String genreOne=infoIds.get(0).getKey();
          String genreTwo=infoIds.get(1).getKey();
          String genreThree=infoIds.get(2).getKey();

          String dorecommendation="select * from do_recommendation(?,?,?)";

            return queryForList(Anime.class,dorecommendation,genreOne,genreTwo,genreThree);
        }
    }

    @Override
    public List<Ratingrecord> searchHistory(String user_id) {
        String sql="select * from filtrate_for_history(?)";

        return queryForList(Ratingrecord.class,sql,user_id);


    }
}


